package com.jmu.medicineknows.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmu.medicineknows.dto.SaleRecordsDto;
import com.jmu.medicineknows.entity.*;
import com.jmu.medicineknows.mapper.*;
import com.jmu.medicineknows.service.SaleRecordService;
import com.jmu.medicineknows.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ACER
 */
@Slf4j
@Service
public class SaleRecordServiceImpl extends ServiceImpl<SaleRecordMapper, SaleRecord> implements SaleRecordService {

    @Resource
    private SaleCountMapper saleCountMapper;
    @Resource
    private SaleDateMapper saleDateMapper;
    @Resource
    private ShoppingMapper shoppingMapper;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private SaleRecordMapper saleRecordMapper;
    @Resource
    private DrugMapper drugMapper;

    @Override
    @Transactional
    public Result orderAdd(SaleRecord saleRecord) {
        LambdaQueryWrapper<DrugInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DrugInfo::getId,saleRecord.getCode());
        DrugInfo drugInfo = drugMapper.selectOne(lambdaQueryWrapper);
        UpdateWrapper<DrugInfo> updateWrapper = new UpdateWrapper<>();
        int lastNum = drugInfo.getNum() - saleRecord.getTotal();
        if(lastNum < 0){
            return Result.failure(405,"库存不足");
        }
        drugInfo.setNum(lastNum);
        updateWrapper.set("num",lastNum);
        updateWrapper.eq("id",saleRecord.getCode());
        drugMapper.update(drugInfo,updateWrapper);

        if ("".equals(saleRecord.getNumber())) {
            return Result.failure(400, "医保卡号错误！");
        }
        saleRecord.setPaid(saleRecord.getReceivable());
        Long code = redisIdWorker.nexId("order");
        saleRecord.setCode(code.toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEEE");
        String currentDate = sdf.format(new Date());
        saleRecord.setDate(currentDate);
        log.info("salesRecord = " + saleRecord);
        //添加sales_date表信息
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf1.format(new Date());
        LambdaQueryWrapper<SaleDate> salesDateQueryWrapper = new LambdaQueryWrapper<>();
        salesDateQueryWrapper.eq(SaleDate::getDate, nowDate);
        SaleDate saleDate = saleDateMapper.selectOne(salesDateQueryWrapper);
        if (saleDate == null) {
            //表中今日的销售记录，新增记录
            saleDate = new SaleDate();
            saleDate.setDate(nowDate);
            saleDate.setTotal(String.valueOf(saleRecord.getReceivable()));
            System.out.println(saleDate);
            saleDateMapper.insert(saleDate);
        } else {
            //表中有今日的销售记录，销售额增加
            String totalStr = saleDate.getTotal();
            double total = Double.parseDouble(totalStr);
            saleDate.setTotal(String.valueOf((total + saleRecord.getReceivable())));
            saleDateMapper.update(saleDate, salesDateQueryWrapper);
        }
        //添加sales_count表信息
        DecimalFormat df = new DecimalFormat("#.00");
        double price = saleRecord.getReceivable() / saleRecord.getTotal();
        String priceFormat = df.format(price);
        LambdaQueryWrapper<SaleCount> saleCountQueryWrapper = new LambdaQueryWrapper<>();
        saleCountQueryWrapper.eq(SaleCount::getName, saleRecord.getName());
        SaleCount saleCount = saleCountMapper.selectOne(saleCountQueryWrapper);
        if (saleCount == null) {
            //表中无此药品的销售记录，新增记录
            saleCount = new SaleCount();
            saleCount.setName(saleRecord.getName());
            saleCount.setNumber(String.valueOf(saleRecord.getTotal()));
            saleCount.setPrice(priceFormat);
            saleCount.setTotal(String.valueOf(saleRecord.getReceivable()));
            saleCountMapper.insert(saleCount);
        } else {
            //表中有此药品的销售记录，销售额增加
            double total = Double.parseDouble(saleCount.getTotal());
            int number = Integer.parseInt(saleCount.getNumber());
            saleCount.setTotal(String.valueOf(total + saleRecord.getReceivable()));
            saleCount.setNumber(String.valueOf(number + saleRecord.getTotal()));
            saleCountMapper.update(saleCount, saleCountQueryWrapper);
        }
        //添加sales_record表信息
        this.save(saleRecord);
        return Result.defaultSuccess("下单成功");
    }

    @Override
    public Result addToCart(ShoppingCart shoppingCart) {
        if ("".equals(shoppingCart.getUid())) {
            return Result.failure(400, "医保卡号错误！");
        }
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUid, shoppingCart.getUid()).eq(ShoppingCart::getName, shoppingCart.getName());
        System.out.println(shoppingMapper.selectCount(wrapper));
        int count = 0;
        if (shoppingMapper.selectCount(wrapper) == 0) {
            return Result.defaultSuccess(shoppingMapper.insert(shoppingCart));
        } else {
            ShoppingCart shoppingCart1 = shoppingMapper.selectOne(wrapper);
            shoppingCart.setNumber(shoppingCart.getNumber() + shoppingCart1.getNumber());
            return Result.defaultSuccess(shoppingMapper.update(shoppingCart, wrapper));
        }

    }

    @Override
    public Result getRecords(SaleRecordsDto saleRecordsDto) {
        IPage<SaleRecord> page = new Page<>(saleRecordsDto.currentPage, saleRecordsDto.pageSize);
        LambdaQueryWrapper<SaleRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(saleRecordsDto.getNumber())) {
            queryWrapper.eq(SaleRecord::getNumber, saleRecordsDto.getNumber());
        }
        if (StringUtils.hasText(saleRecordsDto.getStart()) &&
                StringUtils.hasText(saleRecordsDto.getEnd())) {
            queryWrapper.between(SaleRecord::getDate, saleRecordsDto.start, saleRecordsDto.end);
        } else if (StringUtils.hasText(saleRecordsDto.start)) {
            queryWrapper.ge(SaleRecord::getDate, saleRecordsDto.getStart());
        } else if (StringUtils.hasText(saleRecordsDto.end)) {
            queryWrapper.le(SaleRecord::getDate, saleRecordsDto.getEnd());
        }
        IPage<SaleRecord> recordIPage = saleRecordMapper.selectPage(page, queryWrapper);
        return Result.defaultSuccess(recordIPage);
    }

    @Override
    public Result countPay(SaleRecordsDto saleRecordsDto) {
        LambdaQueryWrapper<SaleRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(saleRecordsDto.getNumber())) {
            queryWrapper.eq(SaleRecord::getNumber, saleRecordsDto.getNumber());
        } else {
            return Result.defaultSuccess(null);
        }
        List<SaleRecord> saleRecords = saleRecordMapper.selectList(queryWrapper);
        float count = 0;
        for (SaleRecord saleRecord : saleRecords) {
            count += saleRecord.getPaid();
        }
        return Result.defaultSuccess(count);
    }
}
